package com.threegroup.web.listener;

import com.threegroup.common.dao.OrdersDao;
import com.threegroup.common.entity.OrdersEntity;
import com.threegroup.common.redis.RedisConf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private OrdersDao ordersDao;


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {

        // 获取到失效的 key，进行取消订单业务处理
        String expiredKey = message.toString();
        String strOrderKey = RedisConf.ORDER + RedisConf.SEGMENTATION;
        //如果是Order:开头的key，进行处理
        if(expiredKey.startsWith(strOrderKey)){
            String orderNumber = expiredKey.substring(strOrderKey.length());
            OrdersEntity ordersEntity = ordersDao.selectByNumber(orderNumber);
            if(ordersEntity.getStatus()==1){
                ordersEntity.setStatus(5);
            }
            ordersDao.updateByPrimaryKeySelective(ordersEntity);
            System.out.println("==>  单号:"+ordersEntity.getNumber()+"过期,该订单取消");
        }

    }

}
